package com.agile.leetcode.easy.bigNumCalculate;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 大数字的运算
 *
 * @Author:ChenZhangKun
 * @Date: 2021/5/9 21:46
 */
public class BigNumAdd {
    private static final Pattern PATTERN = Pattern.compile("[\\d]+");

    public static void main(String[] args) {
        String num1 = "7777";
        String num2 = "8888";
        BigNumAdd add = new BigNumAdd();
        String result = add.bigNumAdd(num1, num2);
        System.out.println(result);
    }

    /**
     * 计算两个大数字
     *
     * @param num1
     * @param num2
     * @return
     */
    public String bigNumAdd(String num1, String num2) {
        // 正则判断是否都是数字
        Matcher matcher = PATTERN.matcher(num1);
        Matcher matcher1 = PATTERN.matcher(num2);
        if (!matcher.matches() || !matcher1.matches()) {
            throw new RuntimeException("请输入正确数字");
        }
        // 拿到长度
        int length1 = num1.length() - 1;
        int length2 = num2.length() - 1;
        // 拿到字符数组
        char[] charNum1 = num1.toCharArray();
        char[] charNum2 = num2.toCharArray();
        // 定义余数
        int remainNum = 0;
        // 定义拼接字符串
        StringBuilder builder = new StringBuilder();
        // 循环
        while (length1 >= 0 || length2 >= 0) {
            // 拿到数组
            int n1 = length1 >= 0 ? (charNum1[length1--] - '0') : 0;
            int n2 = length2 >= 0 ? (charNum2[length2--] - '0') : 0;
            // 相加
            int num = n1 + n2 + remainNum;
            // 有没有进位
            remainNum = num / 10;
            builder.append(num % 10);
        }
        // 是否需要进位
        if (remainNum > 0) {
            builder.append(remainNum);
        }
        // 输出
        return builder.reverse().toString();
    }
}
